﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace customDgv
{
 public partial class ucMy : UserControl
 {
  public ucMy()
  {
   InitializeComponent();
  }

  private List<MyClass> lst = new List<MyClass>();

  private void dgvList_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
  {
   if (lst != null && e.RowIndex >= 0 && lst.Count > e.RowIndex)
   {
    MyClass p = lst[e.RowIndex];
    switch (e.ColumnIndex)
    {
     case 0: e.Value = p.a; break;
     case 1: e.Value = p.b; break;
     default: e.Value = "???"; break;
    }
   }
  }

  public MyClass Selected
  {
   get
   {
    if (dgvList.CurrentCell != null
      && dgvList.CurrentCell.RowIndex >= 0
      && lst.Count > dgvList.CurrentCell.RowIndex)
    {
     return lst[dgvList.CurrentCell.RowIndex];
    }
    else
     return null;
   }
  }

  public delegate void zChanged(MyClass p);
  private zChanged _fun = null;

  public void zAdd(MyClass p)
  {
   lst.Add(p);
   dgvList.RowCount = lst.Count;
   dgvList.Refresh();
  }

  public void zRegister(zChanged fun) { _fun = fun; }

  private void dgvList_SelectionChanged(object sender, EventArgs e)
  {
   if (_fun != null
    && dgvList.CurrentCell.RowIndex >= 0
    && lst.Count > dgvList.CurrentCell.RowIndex)
   {
    _fun(lst[dgvList.CurrentCell.RowIndex]);
   }
  }

  private object o = new object();
  public void zDel(MyClass p)
  {
   lock (o)
   {
    if (lst.Contains(p))
    {
     lst.Remove(p);
     dgvList.RowCount = lst.Count;
     dgvList.Refresh();
    }
   }
  }


 }
}
